package com.cqie.practicaltraining.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.practicaltraining.config.exception.BusinessException;
import com.cqie.practicaltraining.config.result.R;
import com.cqie.practicaltraining.config.util.JwtTokenUtil;
import com.cqie.practicaltraining.domain.Users;
import com.cqie.practicaltraining.dto.*;
import com.cqie.practicaltraining.service.UserService;
import com.cqie.practicaltraining.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

/**
 * @author 9977
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2024-12-26 10:47:28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Users> implements UserService {
    @Autowired
    private UserDetailServiceImpl userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    public R login(UserDto userDto) {
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getUserName, userDto.getUserName());
        Users user = getOne(wrapper);
        if (user == null) {
            return R.Failed("账号或密码错误，请重新输入");
        }
        if(user.getStatus()==0)
            return R.Failed("该用户已被封禁");
        // 获取到UserDetails
        UserDetails userDetails = userDetailsService.loadUserByUsername(userDto.getUserName());
        // 如果密码匹配不一致
        if (!passwordEncoder.matches(userDto.getPassword(), userDetails.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        // 登录成功后将token返回给前端
        String token = jwtTokenUtil.generateToken(userDetails.getUsername());

        // 将用户名和Token存储到Redis中
        String usernameKey = "username";
        String tokenKey = "token";
        redisTemplate.opsForValue().set(usernameKey, userDetails.getUsername());
        redisTemplate.opsForValue().set(tokenKey, token);
        return R.Success("登录成功", token);
    }

    @Override
    public R logout() {
        String usernameKey = "username";
        String tokenKey = "token";
        try {
            // 批量删除缓存
            Long deletedCount = redisTemplate.delete(Arrays.asList(usernameKey, tokenKey));

            if (deletedCount == 2) {
                return R.Success("缓存已成功销毁");
            } else {
                return R.Success("部分缓存销毁失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("缓存销毁失败", e);
        }
    }

    @Override
    public R getCurrentUser() {
        String usernameKey = "username";
        String name = (String) redisTemplate.opsForValue().get(usernameKey);
        if (name == null) {
            return R.Failed("用户未登录");
        } else {
            QueryWrapper<Users> wrapper = new QueryWrapper<>();
            wrapper.eq("user_name", name);
            Users user = getOne(wrapper);
            if (user == null) {
                return R.Failed("用户不存在");
            }
            return R.Success("用户数据", user);
        }
    }

    @Override
    public R addUser(AddUserDto addUserDto) {
        Users user = new Users();
        LambdaQueryWrapper<Users> Wrapper = new LambdaQueryWrapper<>();
        Wrapper.orderByDesc(Users::getUserId).last("LIMIT 1");
        Users lastUser = getOne(Wrapper);
        int number = (lastUser != null) ? (int) (lastUser.getUserId() + 1) : 1;
        String formattedNumber = String.format("%04d", number);
        user.setUserName("YZ" + formattedNumber);
        String lastSixDigits = addUserDto.getPhone().substring(addUserDto.getPhone().length() - 6);
        String passwordEncode = passwordEncoder.encode(lastSixDigits);
        user.setPassword(passwordEncode);
        user.setName(addUserDto.getName().trim());
        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Users::getPhone, addUserDto.getPhone());
        if (getOne(lambdaQueryWrapper) != null) {
            return R.Failed("该手机号已存在");
        }
        user.setPhone(addUserDto.getPhone());
        user.setStatus(addUserDto.getStatus());
        Date date = new Date();
        user.setCreateTime(date);
        if (save(user)) {
            return R.Success("添加成功");
        }
        return R.Failed("添加失败");
    }

    @Override
    public R getUserPageByCondition(SelectDto selectDto) {
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(selectDto.getName() != null, Users::getName, selectDto.getName())
                .like(selectDto.getStatus() != null, Users::getStatus, selectDto.getStatus())
                .like(selectDto.getPhone() != null, Users::getPhone, selectDto.getPhone());
        IPage<Users> page = new Page<>(selectDto.getPageNumber(), selectDto.getPageSize());
        IPage<Users> resultPage = page(page, wrapper);
        PageResult<Users> result = new PageResult<>(resultPage.getRecords(), selectDto.getPageSize(), selectDto.getPageNumber(), resultPage.getTotal());
        if (!result.getRecords().isEmpty())
            return R.Success("查询成功", result);
        return R.Failed("暂无数据");
    }

    @Override
    public R updateUser(UpdateUserDto users) {
        // 检查是否存在其他用户使用了相同的 name
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getName, users.getName())
                .ne(Users::getUserId, users.getUserId());
        if (getOne(wrapper) != null) {
            return R.Failed("该用户名已存在");
        }
        // 检查是否存在其他用户使用了相同的 phone
        LambdaQueryWrapper<Users> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Users::getPhone, users.getPhone())
                .ne(Users::getUserId, users.getUserId());
        if (getOne(wrapper1) != null) {
            return R.Failed("该手机号已存在");
        }
        // 更新用户信息
        Users users1 = new Users();
        users1.setUpdatedTime(new Date());
        String lastSixDigits = users.getPhone().substring(users.getPhone().length() - 6);
        String passwordEncode = passwordEncoder.encode(lastSixDigits);
        users1.setPassword(passwordEncode);
        users1.setName(users.getName());
        users1.setPhone(users.getPhone());
        users1.setStatus(users.getStatus());
        users1.setUserId(users.getUserId());
        if (updateById(users1)) {
            return R.Success("修改成功");
        }
        return R.Failed("修改失败");
    }

    @Override
    public R changeUserStatus(Integer userId) {
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getUserId, userId);
        if (getOne(wrapper) == null)
            return R.Failed("用户不存在");
        Users user = new Users();
        if (getOne(wrapper).getStatus() == 1)
            user.setStatus(0);
        else
            user.setStatus(1);
        user.setUserId(Long.valueOf(userId));
        if (updateById(user))
            return R.Success("修改成功");
        return R.Failed("修改失败");
    }

}




